import React, { Component } from 'react'
export default class Home extends Component {

    state = {
        // 搜索关键词
        keywords: '',
        // 新闻列表
        newsList: [],
        // 搜索结果
        result: []
    }
    UNSAFE_componentWillMount() {
        const arr = new Array(200);
        arr.fill('hello react-v18!');
        this.state.newsList = arr;
    }

    search(e) {
        // 紧急更新
        this.setState({ keywords: e.target.value });
        if (e.target.value.length === 0) {

            return this.setState({
                result: []
            });;
        }
        // 将搜索关键词高亮显示
        const result = this.state.newsList.map(item => {
            const regex = new RegExp(`(${this.state.keywords})`, 'gi');
            return item.replace(regex, "<span style='color:red'>" + this.state.keywords + "</span>");
        });
        // 延迟执行非紧急更新
        React.startTransition(() => {
            // 非紧急更新
            this.setState({
                result
            });
        });
    }

    render() {
        return (
            <div>
                <h1>Home组件</h1>
                <input value={this.state.keywords} type="text" placeholder='请输入关键词' onChange={(e) => this.search(e)} />
                <hr />
                <ol>
                    {
                        this.state.result.map((item, index) => <li key={index} dangerouslySetInnerHTML={{ __html: item }}></li>)
                    }
                </ol>
            </div>
        )
    }
}
